package com.lebang.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.lebang.common.util.ShowDateUtil;
import com.lebang.component.RedisClient;
import com.lebang.component.RedisSdkClient;
import com.lebang.component.UMengPushComponent;
import com.lebang.entity.RequestHeaders;
import com.lebang.entity.member.LbbMember;
import com.lebang.entity.member.LbbMemberRecord;
import com.lebang.entity.member.LbbMemberTrade;
import com.lebang.entity.task.TaskScreenshot;
import com.lebang.mapper.LbbMemberRecordMapper;
import com.lebang.mapper.LbbMemberTradeMapper;
import com.lebang.mapper.TaskScreenshotMapper;
import com.lebang.model.MoneyCategory;
import com.lebang.model.Whether;
import com.lebang.model.enums.InviteEnum;
import com.lebang.model.enums.buss.RecordStatus;
import com.lebang.model.enums.buss.TaskCategory;
import com.lebang.model.enums.buss.TaskStatus;
import com.lebang.service.MemberNewTaskService;
import com.lebang.service.MemberWalletService;
import com.lebang.service.TaskScreenshotService;
import com.lebang.service.buss.MemberService;
import com.lebang.service.buss.MemberTradeService;
import com.lebang.service.buss.WalletService;
import com.lebang.service.sys.DictService;
import com.lebangweb.common.TextUtil;
import com.lebangweb.response.JsonData;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import static com.lebang.model.RedisKey.NEW_HAND_TASK;
import static com.lebang.service.WebApiService.NEW_WEB_TASK;
import static com.lebang.service.WebApiService.WEB_TASK;

@Aspect
@Component
public class RecordAop {
    private static final Logger log = LoggerFactory.getLogger(RecordAop.class);
    @Autowired
    private LbbMemberRecordMapper lbbMemberRecordMapper;
    @Autowired
    private MemberNewTaskService taskService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private LbbMemberTradeMapper lbbMemberTradeMapper;
    @Autowired
    private MemberTradeService tradeService;
    @Autowired
    private WalletService walletService;
    @Autowired
    private MemberWalletService memberWalletService;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private DictService dictService;
    private static final String TASK_ID = "task_by_newhand";
    @Autowired
    private UMengPushComponent uMengPushComponent;
    @Autowired
    private TaskScreenshotService taskScreenshotService;
    @Autowired
    private RedisSdkClient redisSdkClient;

    @Pointcut(value = "execution(* com.lebang.service.task.TaskService.pull(..))")
    public void pointcutDeclaration() {
    }

    @Pointcut(value = "execution(* com.lebang.service.task.TaskService.push(..))")
    public void pushCheck() {
    }

    /**
     * 任务审核完成切面
     *
     * @param joinPoint
     * @param obj
     */

    @AfterReturning(returning = "obj", pointcut = "execution(* com.lebang.service.task.TaskService.examineAndVerify(..))")
    public void doAfterReturning(JoinPoint joinPoint, Object obj) {
        Object[] args = joinPoint.getArgs();
        // 参数值
        List<String> list = (List<String>) args[0];
        // 参数名
        int i = Integer.parseInt(obj.toString());
        String taskId = dictService.selectByKeyName(TASK_ID).getKeyvalue();
        try {
            JSONObject map = JSON.parseObject(taskId);

            List<LbbMemberRecord> recordList = lbbMemberRecordMapper.findCheckListByid(list);
            recordList.forEach(vo -> {
                if (i == 1 && vo.getStatus().equals(TaskStatus.CheckSuccess)) {

//                switch (vo.getCategory()) {
//                    case Common:
//                        taskService.pushRecord(Common, vo.getMemberId());
//                        memberInviteDetailService.checkSosoTask(vo.getMemberId(), vo);
//                        break;
//                    case Soso:
//                        taskService.pushRecord(Common, vo.getMemberId());
//                        memberInviteDetailService.checkSosoTask(vo.getMemberId(), vo);
//                        break;
//                    case Comments:
//                        taskService.pushRecord(Common, vo.getMemberId());
//                        memberInviteDetailService.checkSosoTask(vo.getMemberId(), vo);
//                        break;
//                    default:
//                        break;
//                }
                    int o = map.getIntValue(vo.getTaskId());
                    if (o != 0) {
                        taskService.addRecord(o, vo.getMemberId());
                    }

                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 用户提现成功切面
     *
     * @param joinPoint
     * @param obj
     */

    @AfterReturning(returning = "obj", pointcut = "execution(* com.lebang.controller.buss.AppliesController.staffPay(..))")
    public void cash(JoinPoint joinPoint, Object obj) {
        Object[] args = joinPoint.getArgs();
        Long id = (Long) args[2];
        JsonData jsonData = (JsonData) obj;
        //只处理转账成功的
        LbbMemberTrade trade = lbbMemberTradeMapper.selectByPrimaryKey(id);
        LbbMember member = memberService.selectMemberById(trade.getMemberId());
        if (!jsonData.isSuccess()) {
            return;
        }

        if (member == null) {
            log.info("用户不存在，直接退出");
            return;
        }
        //redis加钱进去
        //tradeService.addInCashRedis(trade.getMemberId(),trade.getAmount());
        //mysql持久化
        memberWalletService.outLayMoney(trade.getMemberId(),trade.getAmount());

    }

    @Autowired
    private TaskScreenshotMapper taskScreenshotMapper;
    /**
     * 领取任务之前规则判断
     * 一个人只能有一个任务
     */

    @Around(value = "pointcutDeclaration()")
    public Object beforeMethod(ProceedingJoinPoint pjp) throws Throwable {
        Object[] args = pjp.getArgs();
        String memberId = args[0].toString();
        String taskId = args[4].toString();
        RequestHeaders header= (RequestHeaders) args[2];
        int count = lbbMemberRecordMapper.checkMemberRecordStatus(memberId, TaskStatus.WaitSumbit.name());
        int check=lbbMemberRecordMapper.checkRecordByImei(header.getImei(),taskId);
        if(check>0){
            RecordStatus recordStatus = RecordStatus.HAS_RECORD;
            recordStatus.setObject("records");
            return recordStatus;
        }
        String phone = memberService.getPhoneById(memberId);
        if(lbbMemberRecordMapper.checkRecordByPhone(phone,taskId)!=null){
            RecordStatus recordStatus = RecordStatus.PHONE_EXIST;
            recordStatus.setObject("record");
            return recordStatus;
        }
        if (count > 0) {
            LbbMemberRecord records = lbbMemberRecordMapper.selectByMemberId(memberId);

            //是否超时
            if (records !=null){
                TaskScreenshot taskScreenshot = taskScreenshotMapper.selectByTaskId(records.getTaskId());
                if (overTime(records.getCreateTime(), Optional.ofNullable(taskScreenshot.getReleaseTime()).orElse(30))){
                    return pjp.proceed();
                }
            }

            RecordStatus recordStatus = RecordStatus.EXIT;
            recordStatus.setObject(records);
            return recordStatus;
        } else {
            return pjp.proceed();
        }
    }
    public Boolean overTime(Date time, Integer releaseTime) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime overtime = LocalDateTime.parse(ShowDateUtil.afterMinute(time, releaseTime), df);
        if (overtime.isAfter(LocalDateTime.now())) {
            return false;
        }
        return true;
    }


    /**
     * 提交任务之前规则判断
     * 判断用户提交参数是否正确
     */

    @Around(value = "pushCheck()")
    public Object pushCheck(ProceedingJoinPoint pjp) throws Throwable {
        Object[] args = pjp.getArgs();

        //判断该任务是否为系统配置的特殊任务30秒自动完成 新手任务的截图任务
        LbbMemberRecord record = (LbbMemberRecord) args[1];
        String taskId = dictService.selectByKeyName(TASK_ID).getKeyvalue();
        if (!TextUtil.isEmpty(taskId) && !record.getCategory().equals(TaskCategory.Soso)) {
            try {
                JSONObject map = JSON.parseObject(taskId);
                int o = map.getIntValue(record.getTaskId());
                if (o != 0) {
                    //增加一个30秒后自动任务成功的事件
                    //redisClient.setex(NEW_HAND_TASK + record.getId(), record.getId().toString(), 30);
                    redisSdkClient.setex(NEW_HAND_TASK + record.getId(), record.getId().toString(), 30);
                    //return RecordStatus.PUSH_SUCCESS;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        if (!record.getCategory().equals(TaskCategory.Soso)) {
            Object obj=args[3];
            if(obj==null){
                return RecordStatus.RESULT_ERROR;
            }
            String result = args[3].toString();
            RecordStatus recordStatus = RecordStatus.RESULT_ERROR;
            recordStatus.setObject(result);
            try {

                JSONArray jsonObject = JSON.parseArray(result);
                if (jsonObject == null) {
                    return recordStatus;
                }
                uMengPushComponent.sendTask("咸鱼审核", "亲你有新审核任务待处理哟");
            } catch (JSONException e) {
                return recordStatus;
            }
        }


        return pjp.proceed();

    }

    /**
     * 任务新增或修改后清楚任务池缓存
     */
    @AfterReturning(returning = "obj", pointcut = "execution(* com.lebang.service.task.TaskService.insertTask(..)) ||execution(* com.lebang.service.task.TaskService.updateTask(..))")
    public void record(JoinPoint joinPoint, Object obj) {
                //redisClient.del(WEB_TASK);
                //redisClient.del(NEW_WEB_TASK);
                redisSdkClient.del(WEB_TASK);
                redisSdkClient.del(NEW_WEB_TASK);
        try{
            Object[] args = joinPoint.getArgs();
            Object object = args[0];
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(object));
            String taskId = jsonObject.getString("taskId");

            TaskScreenshot taskScreenshot = JSON.parseObject(jsonObject.getString("taskScreenshot"),TaskScreenshot.class);
            if(taskScreenshot == null){
                return;
            }
            //新增修改截图任务总表
            TaskScreenshot taskScreen = taskScreenshotService.selectByTaskId(taskId);
            if(taskScreen==null){
                taskScreenshot.setTaskId(taskId);
                taskScreenshotService.insert(taskScreenshot);
            }else{
                taskScreenshot.setId(taskScreen.getId());
                taskScreenshotService.update(taskScreenshot);
            }
            //新增修改任务标签关系表
            taskScreenshotService.deleteTagRelation(taskId);
            if(!TextUtil.isEmpty(taskScreenshot.getTaskTagIds())){
                taskScreenshotService.insertTagRelation(taskId,taskScreenshot.getTaskTagIds());
            }
        }catch (Exception e){
            log.error("新增修改截图任务表出错:"+e.getMessage());
            e.printStackTrace();
        }

    }


    /**
     * 删除截图任务后删除截图任务总表和关系表
     */
    @AfterReturning(returning = "obj", pointcut = "execution(* com.lebang.service.task.TaskService.deleteTask(..))")
    public void afterTaskDelete(JoinPoint joinPoint, Object obj) {
        try{
            Object[] args = joinPoint.getArgs();
            Object object = args[0];
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(object));
            String taskId = jsonObject.getString("taskId");

            //删除截图任务和任务关系表
            TaskScreenshot taskScreen = taskScreenshotService.selectByTaskId(taskId);
            if(taskScreen!=null){
                taskScreen.setHasDeleted("True");
                taskScreenshotService.update(taskScreen);
            }
            taskScreenshotService.deleteTagRelation(taskId);
        }catch (Exception e){
            log.error("删除截图任务和关系表出错:"+e.getMessage());
            e.printStackTrace();
        }

    }


    /**
     * 返利完成切面
     *
     * @param joinPoint
     * @param obj
     */

    @AfterReturning(returning = "obj", pointcut = "execution(* com.lebang.service.buss.MemberTradeService.addMoney(..))")
    public void income(JoinPoint joinPoint, Object obj) {
        try {
            Object[] args = joinPoint.getArgs();
            MoneyCategory moneyCategory= (MoneyCategory) args[7];
            if(moneyCategory.getIsMaster().equals(Whether.NO)){
                return;
            }
           RequestHeaders header= (RequestHeaders) args[5];
            String title= (String) args[2];String remark= (String)args[3];
            //这个任务奖励的金额
            BigDecimal money = new BigDecimal((int) args[1]).divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN);
            //当前用户信息
            LbbMember member = memberService.getMemberById((String) args[0]);
            if(member.getInviteVersion()!=null&&member.getInviteVersion()!=InviteEnum.OLD_VERSION.getIndex()){
                return;
            }
            if (!TextUtil.isEmpty(member.getInviterId())) {
                //用户的师傅信息获取
                LbbMember master = memberService.getMemberById(member.getInviterId());
                if (master != null) {
                    //徒弟的返利百分比
                    int mas = dictService.selectIntByKeyName("sf_rebate");
                    walletService.rebateToMaster(member, master, money.multiply(new BigDecimal(mas)).divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN),
                            0,header,title,remark);
                    if(master.getInviteVersion()!=null&&master.getInviteVersion()!=InviteEnum.OLD_VERSION.getIndex()){
                        return;
                    }
                    if (!TextUtil.isEmpty(master.getInviterId())) {
                        //用户师傅的师傅信息获取
                        LbbMember bigMaster = memberService.getMemberById(master.getInviterId());
                        if (bigMaster != null) {
                            int bigMas = dictService.selectIntByKeyName("td_rebate");
                            walletService.rebateToMaster(member, bigMaster, money.multiply
                                    (new BigDecimal(bigMas)).divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN), 1,header,title,remark);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("返利报错");
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        String str="f9bdeb56f9e74d958e2e7c7b359b3ae3";
        String st1="f9bdeb56f9e74d958e2e7c7b359b3ae3";
       // System.out.println(str.equals(st1));
    }
}
